<template>
  <div class="rightnav">
    <el-tabs v-model="activeTab" class="custom-tabs" @tab-change="handleTabChange">
      <el-tab-pane label="⚙️ 常规" name="static">
        <div class="tab-content">
          <el-form :model="svg_info" label-position="top" size="default">
            <el-form-item label="标识">
              <el-input v-model="svg_info.id" disabled />
            </el-form-item>
            <el-form-item label="类型">
              <el-input v-model="svg_info.type" disabled />
            </el-form-item>
            <el-form-item label="交互类型">
              <el-input v-model="svg_info.active_type" disabled />
            </el-form-item>
            <el-form-item label="名称">
              <el-input placeholder="请输入名称" v-model="svg_info.title" />
            </el-form-item>
            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item label="x轴坐标">
                  <el-input-number v-model="svg_info.svgPositionX" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="y轴坐标">
                  <el-input-number v-model="svg_info.svgPositionY" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="12">
              <el-col :span="12">
                <el-form-item label="大小">
                  <el-input-number v-model="svg_info.size" :step="0.1" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="旋转">
                  <el-input-number v-model="svg_info.angle" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <template v-if="svg_info?.type === 'RectSvg'">
              <el-divider>矩形属性</el-divider>
              <el-form-item label="宽度">
                <el-input-number v-model="svg_info.extend_attr.wh.width" style="width: 100%" />
              </el-form-item>
              <el-form-item label="长度">
                <el-input-number v-model="svg_info.extend_attr.wh.height" style="width: 100%" />
              </el-form-item>
              <el-form-item label="边框">
                <el-input-number v-model="svg_info.extend_attr.stroke.width" style="width: 100%" />
              </el-form-item>
            </template>

            <div v-for="(item, key) in svg_info?.extend_attr" :key="key">
              <el-form-item v-if="item.type != null" :label="item.title">
                <el-input-number v-if="item.type == 'numberinputbox'" v-model="item.val" style="width: 100%" />
                <el-color-picker
                  v-else-if="item.type == 'colorinputbox'"
                  show-alpha
                  v-model="item.val"
                />
                <el-input
                  v-else-if="item.type == 'textinputbox'"
                  :placeholder="`请输入${item.title}`"
                  v-model="item.val"
                />
                <el-input
                  v-else-if="item.type == 'textareainputbox'"
                  :placeholder="`请输入${item.title}`"
                  type="textarea"
                  v-model="item.val"
                />
                <el-radio-group
                  v-model="item.val.selectval"
                  v-else-if="item.type == 'radiogroup'"
                >
                  <el-space>
                    <el-radio
                      v-for="ridioitem in item.val.ridiogroup"
                      :key="ridioitem.value"
                      :label="ridioitem.value"
                      >{{ ridioitem.label }}</el-radio
                    >
                  </el-space>
                </el-radio-group>
                <el-select
                  v-else-if="item.type == 'select'"
                  v-model="item.val.selectval"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(e, i) in item.val.selectgroup"
                    :key="i"
                    :label="e.label"
                    :value="e.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="🔄 动态" name="dynamic">
        <div class="tab-content">
          <el-form label-position="top" size="default">
            <el-form-item label="位号" prop="nodeKey" class="nodekey-form-item">
              <el-radio-group v-model="nodeKeyInputType" style="margin-bottom: 12px; width: 100%;">
                <el-radio label="manual">手动输入</el-radio>
                <el-radio label="select">选择设备</el-radio>
              </el-radio-group>
              
              <!-- 手动输入 -->
              <div v-if="nodeKeyInputType === 'manual'" class="manual-input-wrapper">
                <el-input 
                  v-model="svg_info.nodeKey" 
                  placeholder="deviceCode@propertyCode"
                  @blur="validateNodeKey"
                >
                  <template #prepend>
                    <el-tooltip content="请输入位号，格式为：设备编码@属性编码，例如：device001@temperature" placement="top">
                      <el-icon :size="16" style="cursor: help; color: #909399;">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </template>
                  <template #append>
                    <el-button @click="clearNodeKey" :icon="Delete" />
                  </template>
                </el-input>
              </div>
              
              <!-- 选择设备 -->
              <div v-else class="device-select-group">
                <el-select
                  v-model="selectedDeviceId"
                  placeholder="请选择设备"
                  filterable
                  style="width: 100%; margin-bottom: 12px;"
                  @change="handleDeviceChange"
                  popper-class="device-select-popper"
                >
                  <el-option
                    v-for="device in deviceList"
                    :key="device.id"
                    :label="device.deviceName || device.code"
                    :value="device.id"
                  />
                </el-select>
                
                <el-select
                  v-model="selectedPropertyCode"
                  placeholder="请选择设备属性"
                  filterable
                  style="width: 100%;"
                  @change="handlePropertyChange"
                  popper-class="property-select-popper"
                >
                  <el-option
                    v-for="property in propertyList"
                    :key="property.propertyCode"
                    :label="`${property.propertyName} (${property.propertyCode})`"
                    :value="property.propertyCode"
                  />
                </el-select>
              </div>
              
              <!-- 显示当前位号 -->
              <div v-if="svg_info.nodeKey" class="current-nodekey">
                <el-tag type="success" style="width: 100%; justify-content: center;">当前位号: {{ svg_info.nodeKey }}</el-tag>
              </div>
            </el-form-item>

            <div v-for="(item, key) in svg_info.active" :key="key" class="active-section">
              <el-card shadow="never" :bordered="true">
                <template #header>
                  <span class="section-title">{{ item.title }}</span>
                </template>
                <el-radio-group v-model="item.val.selectval" v-if="item.type == 'radiogroup'">
                  <el-space>
                    <el-radio
                      v-for="ridioitem in item.val.ridiogroup"
                      :key="ridioitem.value"
                      :label="ridioitem.value"
                      >{{ ridioitem.label }}</el-radio
                    >
                  </el-space>
                </el-radio-group>

                <div v-if="item.val.selectval">
                  <div v-for="(alarmList, key) in item.alarm" :key="key" class="alarm-list">
                    <div v-for="(itemsub, key) in alarmList" :key="key">
                      <el-form-item v-if="itemsub.type != null" :label="itemsub.title">
                        <el-input-number
                          v-if="itemsub.type == 'numberinputbox'"
                          v-model="itemsub.val"
                          style="width: 100%"
                        />
                        <el-color-picker
                          v-else-if="itemsub.type == 'colorinputbox'"
                          show-alpha
                          v-model="itemsub.val"
                        />
                        <el-input
                          v-else-if="itemsub.type == 'textinputbox'"
                          :placeholder="`请输入${itemsub.title}`"
                          v-model="itemsub.val"
                        />
                        <el-input
                          v-else-if="itemsub.type == 'textareainputbox'"
                          :placeholder="`请输入${itemsub.title}`"
                          type="textarea"
                          v-model="itemsub.val"
                        />
                        <el-radio-group v-model="itemsub.val.selectval" v-else-if="itemsub.type == 'radiogroup'">
                          <el-space>
                            <el-radio
                              v-for="ridioitem in itemsub.val.ridiogroup"
                              :key="ridioitem.value"
                              :label="ridioitem.value"
                              >{{ ridioitem.label }}</el-radio
                            >
                          </el-space>
                        </el-radio-group>
                        <el-select v-else-if="itemsub.type == 'select'" v-model="itemsub.val.selectval" style="width: 100%">
                          <el-option
                            v-for="opt in itemsub.val.selectgroup"
                            :key="opt.value"
                            :label="opt.label"
                            :value="opt.value"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </el-card>
            </div>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="👆 交互" name="interact">
        <div class="tab-content">
          <div v-for="(item, key) in props.set_svg_info.click_event" :key="key" class="active-section">
            <el-card shadow="never" :bordered="true">
              <el-form label-position="top" size="default">
                <el-form-item :label="item.title">
                  <el-radio-group v-model="item.val.selectval" v-if="item.type == 'radiogroup'">
                    <el-space>
                      <el-radio
                        v-for="ridioitem in item.val.ridiogroup"
                        :key="ridioitem.value"
                        :label="ridioitem.value"
                        >{{ ridioitem.label }}</el-radio
                      >
                    </el-space>
                  </el-radio-group>
                </el-form-item>

                <div v-if="item.val.selectval && item.alarm">
                  <el-form-item label="打开方式">
                    <el-select v-if="item.alarm?.open_style?.type == 'select'" v-model="item.alarm.open_style.val.selectval" style="width: 100%">
                      <el-option
                        v-for="opt in item.alarm.open_style.val.selectgroup"
                        :key="opt.value"
                        :label="opt.label"
                        :value="opt.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="名称">
                    <el-input :model-value="item.alarm?.title" @update:model-value="item.alarm && (item.alarm.title = $event)" placeholder="请输入名称" />
                  </el-form-item>

                  <el-form-item label="弹窗类型">
                    <el-select :model-value="item.alarm?.type" @update:model-value="item.alarm && (item.alarm.type = $event)" style="width: 100%">
                      <el-option label="Iframe嵌入" value="Iframe"></el-option>
                      <el-option label="常规弹框" value="Dialog"> </el-option>
                      <el-option label="脚本执行" value="script"> </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="地址" v-show="item.alarm?.type === 'Iframe'">
                    <el-input :model-value="item.alarm?.url" @update:model-value="item.alarm && (item.alarm.url = $event)" placeholder="请输入地址" />
                  </el-form-item>
                  <el-form-item label="脚本输入" v-show="item.alarm?.type === 'script'">
                    <el-input
                      :model-value="item.alarm?.script"
                      @update:model-value="item.alarm && (item.alarm.script = $event)"
                      type="textarea"
                      autosize
                      placeholder="请输入要执行的脚本"
                    />
                  </el-form-item>
                  <el-form-item label="弹窗选择">
                    <el-select :model-value="item.alarm?.dialogName" @update:model-value="item.alarm && (item.alarm.dialogName = $event)" style="width: 100%">
                      <el-option
                        label="压风机房弹窗"
                        value="../components/Dialog/fanParameters.vue"
                      ></el-option>
                      <el-option
                        label="智慧水务弹窗"
                        value="../components/Dialog/waterDialog.vue"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="是否全屏">
                    <el-select :model-value="item.alarm?.isFullscreen" @update:model-value="item.alarm && (item.alarm.isFullscreen = $event)" style="width: 100%">
                      <el-option label="全屏" :value="true"></el-option>
                      <el-option label="非全屏" :value="false"> </el-option>
                    </el-select>
                  </el-form-item>
                  <el-row :gutter="12">
                    <el-col :span="12">
                      <el-form-item
                        label="弹窗宽度"
                        v-show="
                          !item.alarm?.open_style?.val?.selectval && !item.alarm?.isFullscreen
                        "
                      >
                        <el-input :model-value="item.alarm?.width" @update:model-value="item.alarm && (item.alarm.width = $event)" placeholder="弹窗宽度" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="弹窗高度"
                        v-show="
                          !item.alarm?.open_style?.val?.selectval && !item.alarm?.isFullscreen
                        "
                      >
                        <el-input :model-value="item.alarm?.height" @update:model-value="item.alarm && (item.alarm.height = $event)" placeholder="弹窗高度" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item
                    label="弹窗参数"
                    v-show="
                      !item.alarm?.open_style?.val?.selectval && item.alarm?.type === 'Dialog'
                    "
                  >
                    <el-input :model-value="item.alarm?.paramSet" @update:model-value="item.alarm && (item.alarm.paramSet = $event)" placeholder="弹窗参数" />
                  </el-form-item>
                </div>
              </el-form>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from "vue";
import { ISvgDataLists } from "../Model";
import { getDeviceList, getDeviceRealtimeData } from "../api/business";
import { ElMessage } from "element-plus";
import { Delete, QuestionFilled } from "@element-plus/icons-vue";

const props = defineProps({
  set_svg_info: {
    type: Object as () => ISvgDataLists,
    default: {},
  },
});

// 使用 computed 来响应式地获取 props.set_svg_info
let svg_info = computed(() => props.set_svg_info);
const staticStyle = ref(true);
const dynamicStyle = ref(false);
const clickStyle = ref(false);
const activeTab = ref("static");

// 位号输入相关
const nodeKeyInputType = ref("manual"); // 'manual' | 'select'
const deviceList = ref([]);
const propertyList = ref([]);
const selectedDeviceId = ref("");
const selectedPropertyCode = ref("");

// 初始化设备列表
const initDeviceList = async () => {
  try {
    const res = await getDeviceList({ pageNum: 1, pageSize: 1000 });
    if (res.code === 200) {
      const list = res.data?.records || res.data?.list || res.data || [];
      // 只保留实体表：isVirtual == 1 表示虚拟表
      deviceList.value = list.filter((d: any) => Number(d.isVirtual) !== 1);
    }
  } catch (error) {
    console.error("获取设备列表失败:", error);
  }
};

// 获取设备属性
const handleDeviceChange = async (deviceId: string) => {
  if (!deviceId) return;
  
  try {
    const res = await getDeviceRealtimeData({ deviceId });
    if (res.code === 200) {
      // 取 proPertyList 字段（注意大小写）
      const properties = res.data?.proPertyList || res.data?.propertyList || [];
      
      // 处理属性数据：propertyName 取 name，propertyCode 取 dataFormCode 或 dataCode
      propertyList.value = properties
        .filter(p => p.kind === 1) // 仅保留 kind === 1 的属性
        .map(p => ({
          propertyName: p.name,
          propertyCode: p.dataFormCode || p.dataCode,
          ...p // 保留其他字段
        }));
    }
    selectedPropertyCode.value = ""; // 清空属性选择
  } catch (error) {
    console.error("获取设备属性失败:", error);
    ElMessage.error("获取设备属性失败");
  }
};

// 选择属性
const handlePropertyChange = (propertyCode: string) => {
  if (!selectedDeviceId.value || !propertyCode) return;
  
  // 找到选中的设备
  const device = deviceList.value.find(d => d.id === selectedDeviceId.value);
  if (device) {
    // 生成位号：deviceCode@propertyCode
    svg_info.value.nodeKey = `${device.deviceCode || device.code}@${propertyCode}`;
  }
};

// 清除位号
const clearNodeKey = () => {
  svg_info.value.nodeKey = "";
};

// 校验位号格式
const validateNodeKey = () => {
  const nodeKey = svg_info.value.nodeKey;
  if (!nodeKey) return;
  
  // 校验格式：deviceCode@propertyCode
  const pattern = /^.+@.+$/;
  if (!pattern.test(nodeKey)) {
    ElMessage.warning("位号格式不正确，应为：deviceCode@propertyCode");
  }
};

onMounted(() => {
  initDeviceList();
});

const handleTabChange = (name: string) => {
  if (name === "static") {
    staticStyle.value = true;
    dynamicStyle.value = false;
    clickStyle.value = false;
  } else if (name === "dynamic") {
    staticStyle.value = false;
    dynamicStyle.value = true;
    clickStyle.value = false;
  } else if (name === "interact") {
    staticStyle.value = false;
    dynamicStyle.value = false;
    clickStyle.value = true;
  }
};
</script>

<style lang="scss" scoped>
.rightnav {
  width: 100%;
  height: 100%;
  overflow: auto;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

.custom-tabs {
  padding: 0 8px;
}

.tab-content {
  padding: 12px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    
    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

.active-section {
  margin-bottom: 12px;
  
  .section-title {
    font-weight: 600;
    color: #303133;
  }
}

.alarm-list {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
  
  .el-form-item__label {
    font-weight: 500;
    color: #606266;
    margin-bottom: 8px;
  }
}

:deep(.el-card) {
  border: 1px solid #e4e7ed;
  
  .el-card__header {
    padding: 12px 16px;
    background: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
  }
  
  .el-card__body {
    padding: 16px;
  }
}

:deep(.el-divider__text) {
  background-color: transparent;
  font-weight: 600;
  color: #303133;
}

:deep(.el-input--disabled .el-input__inner) {
  background-color: #f5f7fa;
  color: #909399;
}

.manual-input-wrapper {
  width: 100%;
  
  :deep(.el-input) {
    width: 100%;
  }
}

.device-select-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.current-nodekey {
  margin-top: 12px;
  padding: 8px;
  background-color: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #bfdbfe;
  text-align: center;
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 16px;
  }
}

:deep(.nodekey-form-item) {
  .el-form-item__content {
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .el-select {
    width: 100% !important;
    min-width: 280px;
    
    .el-input__wrapper {
      width: 100% !important;
    }
    
    .el-input {
      width: 100% !important;
    }
  }
  
  .el-input {
    width: 100% !important;
  }
}

/* 下拉选项宽度 */
:deep(.device-select-popper),
:deep(.property-select-popper) {
  min-width: 320px !important;
  max-width: 500px;
  
  .el-select-dropdown__item {
    white-space: normal !important;
    word-break: break-word;
    line-height: 1.5;
    padding: 8px 16px;
    
    span {
      white-space: normal !important;
      word-break: break-word;
    }
  }
}
</style>
